<template>
  <div class="chat-box">
    <div class="chat-header">
      <h3>{{ chat.groupName }}</h3>
    </div>
    <div class="chat-messages" ref="messageContainer">
      <div v-for="(message, index) in messages" :key="index" class="message" :class="{ 'message-self': message.userId === currentUserId }">
        <div class="message-sender">{{ message.userName }}</div>
        <div class="message-content">{{ message.content }}</div>
        <div class="message-time">{{ formatTime(message.createdAt) }}</div>
      </div>
      <div v-if="typingUsers.length > 0" class="typing-indicator">
        {{ typingUsers.join(', ') }} {{ typingUsers.length === 1 ? '正在输入' : '正在输入' }}
      </div>
    </div>
    <div class="chat-input">
      <el-input
        v-model="newMessage"
        placeholder="输入消息..."
        @keyup.enter.native="sendMessage"
        @input="handleTyping"
      >
        <el-button slot="append" icon="el-icon-s-promotion" @click="sendMessage">发送</el-button>
      </el-input>
    </div>
  </div>
</template>

<script>
import signalRService from '@/utils/signalR'
import { getUserId } from '@/utils/auth'
import { getGroupMessages } from '@/api/chat'

export default {
  props: {
    chat: {
      type: Object,
      required: true
    }
  },
  data() {
    return { 
      messages: [],
      newMessage: '',
      currentUserId: getUserId(),
      typingUsers: [],
      typingTimeout: null
    }
  },
  watch: {
    'chat.groupId': {
      handler(newVal) {
        if (newVal) {
          this.loadMessages()
          this.joinChatGroup()
        }
      },
      immediate: true
    }
  },
  created() {
    // 注册SignalR事件处理程序
    signalRService.onMessage(this.handleNewMessage)
    signalRService.onTyping(this.handleTyping)
    signalRService.onUserJoined(this.handleUserJoined)
    signalRService.onUserLeft(this.handleUserLeft)
    signalRService.onError(this.handleError)
  },
  beforeDestroy() {
    // 移除SignalR事件处理程序
    signalRService.removeAllHandlers()
    // 离开群组
    if (this.chat && this.chat.groupId) {
      signalRService.leaveGroup(this.chat.groupId)
    }
  },
  methods: {
    async loadMessages() {
      try {
        const response = await getGroupMessages(this.chat.groupId)
        if (response.code === 20000) {
          this.messages = response.data
          this.$nextTick(() => {
            this.scrollToBottom()
          })
        }
      } catch (error) {
        console.error('加载消息失败:', error)
        this.$message.error('加载消息失败')
      }
    },
    async joinChatGroup() {
      if (this.chat && this.chat.groupId) {
        await signalRService.joinGroup(this.chat.groupId)
      }
    },
    async sendMessage() {
      if (!this.newMessage.trim()) {
        return
      }
      
      const success = await signalRService.sendMessage(this.chat.groupId, this.newMessage)
      if (success) {
        this.newMessage = ''
      }
    },
    handleTyping() {
      if (this.typingTimeout) {
        clearTimeout(this.typingTimeout)
      }
      
      this.typingTimeout = setTimeout(async () => {
        await signalRService.sendTyping(this.chat.groupId)
      }, 500)
    },
    handleNewMessage(data) {
      if (data.groupId === this.chat.groupId) {
        this.messages.push({
          userId: data.userId,
          userName: data.userName || '未知用户',
          content: data.content,
          createdAt: data.createdAt
        })
        this.$nextTick(() => {
          this.scrollToBottom()
        })
      }
    },
    handleTyping(data) {
      if (data.groupId === this.chat.groupId && data.userId !== this.currentUserId) {
        if (!this.typingUsers.includes(data.userName || '未知用户')) {
          this.typingUsers.push(data.userName || '未知用户')
        }
        
        setTimeout(() => {
          this.typingUsers = this.typingUsers.filter(user => 
            user !== (data.userName || '未知用户')
          )
        }, 3000)
      }
    },
    handleUserJoined(data) {
      if (data.groupId === this.chat.groupId) {
        this.$message.info(`${data.userName || '未知用户'} 加入了群组`)
      }
    },
    handleUserLeft(data) {
      if (data.groupId === this.chat.groupId) {
        this.$message.info(`${data.userName || '未知用户'} 离开了群组`)
      }
    },
    handleError(message) {
      this.$message.error(message)
    },
    scrollToBottom() {
      const container = this.$refs.messageContainer
      if (container) {
        container.scrollTop = container.scrollHeight
      }
    },
    formatTime(time) {
      if (!time) return ''
      const date = new Date(time)
      return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
    }
  }
}
</script>

<style scoped>
.chat-box {
  display: flex;
  flex-direction: column;
  height: 100%;
  border: 1px solid #e6e6e6;
  border-radius: 4px;
}

.chat-header {
  padding: 10px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #e6e6e6;
}

.chat-messages {
  flex: 1;
  padding: 10px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
}

.message {
  margin-bottom: 10px;
  max-width: 70%;
  align-self: flex-start;
}

.message-self {
  align-self: flex-end;
}

.message-sender {
  font-size: 12px;
  color: #909399;
  margin-bottom: 2px;
}

.message-content {
  padding: 8px 12px;
  background-color: #f5f7fa;
  border-radius: 4px;
  word-break: break-word;
}

.message-self .message-content {
  background-color: #ecf5ff;
  color: #409EFF;
}

.message-time {
  font-size: 10px;
  color: #c0c4cc;
  margin-top: 2px;
  text-align: right;
}

.chat-input {
  padding: 10px;
  border-top: 1px solid #e6e6e6;
}

.typing-indicator {
  font-size: 12px;
  color: #909399;
  font-style: italic;
  margin: 5px 0;
}
</style>